﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Zhongy
{
    /// <summary>
    /// 本类为网络消息分发中心
    /// </summary>
    public class NetRCenter:IApplication
    {
        IHandler account = new AccountHandler();
        IHandler users = new UserHandler();
        IHandler player = new PlayerHandler();
        IHandler game = new GameHandler();
        IHandler answer = new AnswerHandler();


        private int updateTimerId = -1;
        private Dictionary<ClientPer, long> dicClient2TimeStamp = new Dictionary<ClientPer, long>();

        public NetRCenter()
        {

        }

        public void OnDisconnect(ClientPer client)
        {
            answer.OnDisconnect(client);
            game.OnDisconnect(client);
            player.OnDisconnect(client);

            users.OnDisconnect(client);
            account.OnDisconnect(client);

        }

        public void OnReceive(ClientPer client, SocketReceiveMsg msg)
        {

#if DEBUG_MODEL


#if !PRINT3AND4
            if (msg.MT == 3 || msg.MT == 4) ;
            else
#else

#endif

                Debug.Log(string.Format("<color=red>消息类型MT:    {0}</color>", msg.MT));
#endif

            if (updateTimerId == -1)
            {
                updateTimerId = TimerManager.Instance.AddFixedTimer(1, CheckClientValid, null, 2 * 1000);
            }

            dicClient2TimeStamp[client] = EncodeTool.GetTimestamp(DateTime.Now);

            switch (msg.MT)
            {
                case OpCode.TYPE_TV_CHECK_CLIENT:
                case OpCode.TYPE_CLIENT_DISCONNECT:
                    account.OnReceive(client, msg);
                    break;

                case OpCode.TYPE_SYN_STU_STATUS:
                    users.OnReceive(client, msg);
                    break;

                case OpCode.TYPE_SYN_PLAYER_INFO:
                case OpCode.TYPE_ADD_STU_C:
                case OpCode.TYPE_DEL_STU_C:
                case OpCode.TYPE_STU_DATA:
                    player.OnReceive(client, msg);
                    break;

                case OpCode.TYPE_START_GAME_C:
                case OpCode.TYPE_STOP_GAME_C:
                    game.OnReceive(client, msg);
                    break;

                case OpCode.TYPE_ACK2G:
                case OpCode.TYPE_DEBUG_MSG_C:
                    answer.OnReceive(client, msg);
                    break;

                default:
                    break;

            }
        }

        private int warningRank = -1;

        private IList<ClientPer> removeLst = new List<ClientPer>();
        //todo  这里结构有点混乱
        private UnityEngine.UI.Text showPrompt;

        public UnityEngine.UI.Text GetPrompt
        {
            get
            {
                if (showPrompt == null)
                    showPrompt = GameObject.Find("5miaoText").GetComponent<UnityEngine.UI.Text>();

                return showPrompt;
            }
        }

        void CheckClientValid()
        {

            if (dicClient2TimeStamp.Count <= 0)
                return;

            removeLst.Clear();

            foreach (KeyValuePair<ClientPer, long> item in dicClient2TimeStamp)
            {

                DateTime dt = EncodeTool.NewDate(item.Value);
                float second = (float)(DateTime.Now - dt).TotalSeconds;
                if (second > 5)
                {
                    Debug.Log(string.Format("<color=red>最近消息为{0}</color>", EncodeTool.NewDate(item.Value)));
                    Debug.Log(string.Format("<color=red>当前时间为{0}</color>", DateTime.Now));

                    warningRank++;
                    if (warningRank == 0)
                    {
                        GetPrompt.text = second+"秒未收到消息";
                    }
                    else if(warningRank >2)
                    {
                        GetPrompt.text = string.Empty;
                        removeLst.Add(item.Key);
                        Debug.Log("断    断   断   断   断   断   断   断   断");
                    }

                    Debug.LogError("----------------------------------------------------");
                    Debug.LogError("----------------------------------------------------");
                    Debug.LogError("----------------------------------------------------");
                    Debug.LogError("----------------------------------------------------");
                    Debug.LogError("----------------------------------------------------");
                }
                else
                {
                    warningRank = -1;
                    GetPrompt.text = string.Empty;
                }
                
            }


            //todo 只能符合现在一个client的情况
            foreach (ClientPer key in removeLst)
            {
                dicClient2TimeStamp.Remove(key);

                //GameObject.Find("5miaoText").GetComponent<UnityEngine.UI.Text>().text = "5秒未收到app的消息，主动断连";
                Debug.Log("<color=red>5秒未收到client的消息，主动断连</color>");

                if (BindGameEvent.Game2ClientStop != null)
                    BindGameEvent.Game2ClientStop();

                if (BindGameEvent.GameStop != null)
                    BindGameEvent.GameStop();

                if (BindGameEvent.Game2ClientDisconnect != null)
                    BindGameEvent.Game2ClientDisconnect();

                if (BindGameEvent.GameDisConnect != null)
                    BindGameEvent.GameDisConnect();

            }
        }
    }
}
